package g4p.tests;

import g4p_controls.GWinApplet;
import g4p_controls.GWinData;
import g4p_controls.GWindow;
import processing.core.PApplet;
import processing.core.PImage;

public class Dali extends PApplet {

	private int nbrWindows = 4;
	private float winSizeFactor = 0.3f;
	private int winW, winH;
	
	PImage myImage;
	GWindow window[] = new GWindow[nbrWindows];
	MyWinData mydata;
	
	int imgX, imgY, imgH, imgW;
	
	public void setup(){
		size(100,100);
		
		myImage = loadImage("g4p/dali.jpg");
		imgW = myImage.width;
		imgH = myImage.height;
		imgX = (int) ((2000 - imgW)/2);
		imgY = (int) ((1000 - imgH)/2);
		winW = (int) (imgW * winSizeFactor);
		winH = (int) (imgH * winSizeFactor);
		
		float angle;
		
		for(int i = 0; i < nbrWindows; i++){
			mydata = new MyWinData();
			mydata.px = random(imgX, imgX + imgW - winW);
			mydata.py = random(imgY, imgY + imgH - winH);
			mydata.w = winW;
			mydata.h = winH;
			angle = radians(random(17.0f, 77.0f));
			mydata.vx = sin(angle);
			mydata.vy = cos(angle);
			if(random(1.0f) < 0.5)
				mydata.vx *= -1;
			if(random(1.0f) < 0.5)
				mydata.vy *= -1;
			
			window[i] = new GWindow(this, "", (int)mydata.px,(int)mydata.py,mydata.w,mydata.h, true, null);
			window[i].addData(mydata);
			window[i].addPreHandler(this, "preSquare");
			window[i].addDrawHandler(this, "drawSquare");
			//window[i].embed.noLoop();
			window[i].papplet.frameRate(1);

		}
		
//		System.out.println(screen.getWidth() + " x " + screen.getHeight());
		System.out.println(imgX + " x " + imgY);
	}
	
	public void preSquare(GWinApplet appc, GWinData data){
		System.out.println("pre");
		MyWinData d = (MyWinData)data;
		float npx = d.px + d.vx;
		float npy = d.py + d.vy;
//		d.px += d.vx;
//		d.py += d.vy;
		if(npx < 0){
			npx = 0;
			d.vx *= -1;
		}
		else if (npx + d.w > imgX + imgW){
			npx = imgX + imgW - d.w;
			d.vx *= -1;
		}
		if(npy < 0){
			npy = 0;
			d.vy *= -1;
		}
		else if(npy + d.h > imgY + imgH){
			npy = imgY + imgH - d.h;
			d.vy *= -1;
		}
		if( (int)d.px != (int)npx || (int)d.py != (int)npy){
			appc.owner.setLocation((int)npx,(int)npy);
			redraw();
		}
		d.px = npx;
		d.py = npy;
	}
	
	public void drawSquare(GWinApplet appc, GWinData data){
		MyWinData d = (MyWinData)data;
		System.out.println("draw");
		appc.image(myImage, 0,0, d.w,d.h , 
				(int)(d.px - imgX), (int)(d.py - imgY),
				(int)(d.px - imgX) + d.w,
				(int)(d.py - imgY) + d.h);
	}
	
	/**
	 * Simple class that extends GWinData and holds the data that is specific
	 * to a particular window.
	 * 
	 * @author Peter Lager
	 *
	 */
	class MyWinData extends GWinData {

		public float vx, vy;
		public int w,h;
		public float px,py;
		
		
	}

}
